<template>
  <div>
    <n-grid :x-gap="5">
      <n-grid-item :span="24">
        <n-grid :x-gap="5" y-gap="5">
          <n-grid-item :span="24">
            <div class="image-container">
              <n-image
                  :width="150"
                  :lazy="true"
                  :object-fit="'cover'"
                  v-if="row.imageUrl"
                  :src="fileFunction.getViewFilePathByUserFileId(row.imageUrl)"
              />
              <n-empty v-else description="还未生成">
              </n-empty>
           </div>
          </n-grid-item>
          <n-grid-item :span="12">
            <n-button  size="tiny" secondary   type="primary" :loading="paintLoading" @click="paint(props.row)" block>图片生成</n-button>
          </n-grid-item>
          <n-grid-item :span="12">
            <n-button  size="tiny" secondary   type="primary" :loading="paintLoading" @click="paint(props.row)" block>视频生成</n-button>
          </n-grid-item>
          <n-grid-item :span="12">
            <n-button   size="tiny" secondary   type="primary" :loading="upscaleLoading" @click="upsacle" block>图片放大</n-button>
          </n-grid-item>
          <n-grid-item :span="12">
            <n-button   size="tiny" secondary   type="primary" :loading="upscaleLoading" @click="upsacle" block>暂无</n-button>
          </n-grid-item>
          <n-grid-item :span="12">

            <n-popselect @update:value="uploadPicForMj" v-if=" props.storyPaintConfig && props.storyPaintConfig.paintType==='MJ'" :options="mjUploadOptions" trigger="hover">
              <n-button  size="tiny" secondary   type="info" :loading="uploadLoading" block>上传图片</n-button>
            </n-popselect>
            <n-button v-else size="tiny" secondary   type="info" :loading="uploadLoading"   @click="handleUploadClick" block>上传图片</n-button>

            <n-upload
                :accept="'image/*'"
                :directory="false"
                style="display: none"
                ref="uploadButton"
                :show-file-list="false"
                :custom-request="(uploadOption) =>customRequest(uploadOption,props.row,'single')">
                  <n-button   block :bordered="false"  secondary type="primary" >
                    上传图片
                  </n-button>
              </n-upload>

            <n-upload
                :accept="'image/*'"
                :directory="false"
                style="display: none"
                ref="uploadButtonBatch"
                :show-file-list="false"
                :custom-request="(uploadOption) =>customRequest(uploadOption,props.row,'batch')">
              <n-button   block :bordered="false"  secondary type="primary" >
                上传套图
              </n-button>
            </n-upload>
          </n-grid-item>
          <n-grid-item :span="12">
            <n-button v-if="props.storyPaintConfig && props.storyPaintConfig.paintType==='MJ'" size="tiny" secondary type="info" :loading="inpaintLoading" @click="reCatchPic" block>重新抓取</n-button>
            <n-button  v-else size="tiny" secondary   type="info" :loading="inpaintLoading" @click="repaintModelShow = true" block>局部重绘</n-button>
          </n-grid-item>


        </n-grid>
      </n-grid-item>
    </n-grid>
    <n-modal
      v-model:show="repaintModelShow"
      transform-origin="center"
    >
      <ReapintView :inPaintAction="inpaint" :storyBoard="props.row" :closeAction="updateImage">
      </ReapintView>
    </n-modal>
  </div>

</template>

<script setup lang="ts">
//@ts-ignore
import fileFunction from '@/libs/globalFunction/file.js'
import {NButton, NSpace, UploadCustomRequestOptions} from "naive-ui";
import {storyController} from '@/api/story/story.api'
import {computed, ref} from "vue";
import {useMessage } from 'naive-ui';
import {storyBoardController} from "@/api/controller/story/storyBoard.api";
import ReapintView from "@/components/creator/function/repaint.vue";


const message = useMessage()
const loading = ref(false)
const uploadLoading = ref(false)
const repaintModelShow = ref(false)
const inpaintLoading = ref(false)
const uploadButton =ref(null)
const uploadButtonBatch =ref(null)
const paintLoading = ref(false)
const upscaleLoading = ref(false)
const props = defineProps({
    row: {
        type: Object,
        default: () => {
            return {}
        }
    },
    updateStoryBoardByNum:{
      type: Function,
      required: true
    },
    storyPaintConfig:{
      type: Object,
      required: true,
      default: () => {
        return {}
      }
    }
})

const customRequest = (uploadOption: UploadCustomRequestOptions,item:any,type:string) => {
  const reader = new FileReader();
  //@ts-ignore
  reader.readAsDataURL(uploadOption.file.file);
  reader.onloadend = () => {
    let image = new Image()
    image.src = reader.result
    console.log(image.src)
    const param = {
      storyBoardId: item.id,
      base64Image: image.src.split(';base64,')[1],
      imageType: type
    }
    uploadLoading.value = true
    storyBoardController.uploadStoryBoardImage(param).then(res => {
      if (res.code ===200){
        updateImage()
        window.$message.success('上传成功')
      }
    }).finally(() => {
      uploadLoading.value = false
    })
  };
}

const updateImage = ()=>{
  const orderNums = [props.row.orderNum]
  props.updateStoryBoardByNum(orderNums)
}



const inpaint = async (base64:string, prompt:string , storyBoardId:string) =>{
  // inPaintStoryBoard.value.expandLoding = true
  inpaintLoading.value = true
  repaintModelShow.value = false
  console.log(props.storyPaintConfig)
  if (props.storyPaintConfig.paintType ==='SD') {
    const param = {
      mask: base64,
      prompt: prompt,
      storyBoardId: storyBoardId
    }
    storyBoardController.asyncSDInpaintStoryBoardAndCheck(param, 10 * 60 * 1000).then(res => {
      if (res.taskStatus === 'SUCCESS') {
        updateImage()
      } else {
        window.$notification.error({
          title: "请求异常:",
          content: res.failReason,
          duration: 5000,
          keepAliveOnHover: true
        })
      }
    }).finally(() => {
      inpaintLoading.value = false
    })
  } else if (props.storyPaintConfig.paintType ==='Fooocus'){
    const param = {
      mask: base64,
      prompt: prompt,
      storyBoardId: storyBoardId
    }
    storyBoardController.asyncFooocusInpaintStoryBoardAndCheck(param,10*60*1000).then(res=>{
      if (res.taskStatus === 'SUCCESS') {
        updateImage()
      }else {
        window.$notification.error({
          title: "请求异常:",
          content: res.failReason,
          duration: 5000,
          keepAliveOnHover: true
        })
      }
    }).finally(()=>{
      inpaintLoading.value = false
    })
  }
}


const paint = (row: any) => {
  // 设置当前状态为已提交
  paintLoading.value = true
  storyBoardController.rePaintStoryBoardAndCheck(row.id, 5 * 60 * 1000).then(res => {
    if (res.taskStatus === 'SUCCESS') {
      updateImage()
    }else {
      window.$notification.error({
        title: "请求异常:",
        content: res.failReason,
        duration: 5000,
        keepAliveOnHover: true
      })
    }
  }).finally(() => {
    paintLoading.value = false
  })
}


const upsacle = () => {
  const param = {
    scale: 2,
    upscaleEngine: 'realesrgan',
    modelName: 'realesr-animevideov3',
    skipFlag: false,
    storyBoardId: props.row.id,
  }
  upscaleLoading.value = true
  storyBoardController.upscale(param).then(res => {
    if (res.code === 200) {
      updateImage()
    } else {
      message.error(res.msg)
    }
  }).finally(() => {
    upscaleLoading.value = false
  })
}
const handleUploadClick =()=> {
  uploadButton.value?.openOpenFileDialog()
}

const uploadPicForMj = (uploadType:string) =>{
  if (uploadType === 'single'){
    uploadButton.value?.openOpenFileDialog()
  }else {
    uploadButtonBatch.value?.openOpenFileDialog()
  }
}

const mjUploadOptions = ref([
  {
    label: '单张',
    value: 'single'
  },
  {
    label: '套图',
    value: 'batch'
  }
])

const reCatchPic = () =>{

}
</script>

<style scoped>
.image-container {
  height: 170px; /* 设置容器的固定高度 */
  display: flex; /* 使用Flex布局 */
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中 */
}

.image-container-lite {
  height: 80px; /* 设置容器的固定高度 */
  display: flex; /* 使用Flex布局 */
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中 */
}
</style>
